#----------------------------------------------------------
#		TMP102 TEMPERATURE SENSOR
#		=========================
#
# In this project a TMP102 type I2C compatible temperature
# sensor chip is connected to Raspberry Pi Pico. The temperature
# readings are displayed on the I2C LCD.
#
# Author: Dogan Ibrahim
# File  : TMP102.py
# Date  : October 2022
#------------------------------------------------------------
import utime
from ST7735 import TFT
from sysfont import sysfont
from machine import SPI, Pin, I2C

#
# Initialize the SPI
#
spi = SPI(0, baudrate=20000000, polarity=0, phase=0,
sck=Pin(2), mosi=Pin(3), miso=Pin(4))

tft = TFT(spi, 15, 14, 5)
tft.initg()
tft.rgb(True)

#
# Initialize I2C
#
i2c = machine.I2C(0, scl=Pin(9), sda=Pin(8), freq=100000)
print("i2c address=",i2c.scan())

Device_Address = 0x48			# TMP102 I2C address
PointerReg = 0                          # TMP102 register

#
# This function reads the temperature, extracts degrees Celius
# and returns the temperature to the main calling program
#
def Read():
    data = [0, 0]
    LSB = 0.0625
#    data = i2c.readfrom_mem(Device_Address, PointerReg, 2)
    temp = (data[0] << 4) | (data[1] >> 4)
    if temp > 0x7FF:
        temp = (~temp) & 0xFF
        temp = temp + 1
        temperature = -temp * LSB
    else:
        temperature = temp * LSB
    return(temperature)

#
# Main program reads and displays the temperature every 3 seconds
#
while True:
    Temperature = Read()
    tft.fill(TFT.WHITE)			# Clear screen
    tft.rect((5, 10), (100, 120), TFT.RED)
    tft.text((17, 30),"TEMPERATURE",TFT.BLUE,sysfont,1.1,nowrap=True)
    tft.text((15, 60), "Temp:{:.2f}C".format(Temperature), TFT.BLUE, 
    sysfont, 1.1, nowrap=True)
    utime.sleep(3)
          